package com.haust.leyou.listener;

import com.haust.leyou.config.AliyunSmsPropertiesConfig;
import com.haust.leyou.service.AliyunSendSmsService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Map;

/**
 * @Auther: csp1999
 * @Date: 2020/12/18/14:25
 * @Description: 阿里云SMS短信服务监听器组件(消息消费者)
 */
@Component
public class AliyunSmsListener {

    private static final Logger logger = LoggerFactory.getLogger(AliyunSmsListener.class);

    @Autowired
    private AliyunSendSmsService aliyunSendSmsService;

    @Autowired
    private AliyunSmsPropertiesConfig aliyunSmsPropertiesConfig;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "LEYOU.SMS.QUEUE", durable = "true"),
            exchange = @Exchange(
                    value = "LEYOU.SMS.EXCHANGE",
                    ignoreDeclarationExceptions = "true",
                    type = ExchangeTypes.TOPIC),
            key = {"verifycode.sms"}
    ))
    public void sendMessage(Map<String, String> msg) {

        if (CollectionUtils.isEmpty(msg)) {
            return;
        }

        String phone = msg.get("phone");
        String code = msg.get("code");

        Boolean bool = false;
        if (StringUtils.isNotBlank(phone) && StringUtils.isNotBlank(code)) {
            bool = aliyunSendSmsService.sendMessage(
                    phone,
                    code,
                    aliyunSmsPropertiesConfig.getSignName(),
                    aliyunSmsPropertiesConfig.getTemplateCode());
        }

        if (bool) {
            logger.info("短信发送成功！");
        } else {
            logger.info("短信发送失败！");
        }
    }
}
